# encoding: utf-8
# @author: wangxin
# @software: garner
# @file: forgetPassword.py
# @time: 2025/2/20 11:22
import re
from http.client import responses

from django.contrib.auth import login
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from user import models
from user.models import User


class forgetPasswordView(View):
    def get(self, request):

        return render(request, 'forget_password.html')

    def post(self,request):
        mobile = request.POST.get('mobile')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        sms_code = request.POST.get('sms_code')
        if not all([mobile, password, password2, sms_code]):
            return HttpResponseBadRequest('请输入完整的注册信息')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseBadRequest('请输入正确的手机号码')
        if not re.match(r'^[0-9A-Za-z]{6,20}$', password):
            return HttpResponseBadRequest('请输入6-20位的密码')
        if password != password2:
            return HttpResponseBadRequest('两次密码不一致')
        redis_conn = get_redis_connection('default')
        sms_code_redis = redis_conn.get('sms_code:%s' % mobile)
        if sms_code_redis is None:
            return HttpResponseBadRequest('短信验过期')
        if sms_code != sms_code_redis.decode():
            return HttpResponseBadRequest('短信验证码错误')
        # 保存注册数据

        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            try:
                user = models.User.objects.create_user(username=mobile, mobile=mobile, password=None)  # 初始时不设置密码
                user.set_password(password)  # 使用 Django 的 set_password 方法来安全设置密码


            except Exception as e:
                print(e)
                return HttpResponseBadRequest('修改失败')
        user.set_password(password)
        user.save()
        responses = redirect(reverse('users:login'))

        # 注册成功，重定向到首页
        return responses


